<?php
/**
 * Create by chang
 * Date 2019/12/25
 * Time 15:39
 *
 */

namespace app\common\service;

use app\admin\model\User;
use app\common\model\AgentOrder;
use app\common\model\AgentShip;
use app\common\model\AgentShop;
use app\common\model\BusinessPlan;
use app\common\model\Commission;
use app\common\model\Order;
use app\common\model\Promotion;
use app\common\model\RuleSz;
use app\common\model\TutorMember;
use app\common\model\TutorSaleItem;
use app\common\model\TutorSetting;
use think\Db;
use think\Exception;

class OrderService extends Server {
	
	/**
	 * 根据商品活动判断订单类型
	 * @param $goodsId
	 * @return bool|int
	 * @throws DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	public static function getOrderTypeByActivity($goodsId) {
		//查找正在进行中的大赛
		$plan = Db::name('businessPlan')->where([
			'start_time' => ['elt', time()],
			'end_time' => ['gt', time()],
			'goods_id' => $goodsId,
		])
			->order(['id' => 'desc'])
			->find();
		
		
		if($plan) {
			return [
				'type' => Order::TYPE_PLAN,
				'id' => $plan['id']
			];
		}
		
		//导师
		$tutor = Db::name('tutorSetting')
			->where(['status' => TutorSetting::STATUS_enable, 'goods_id' => $goodsId])
			->order(['id' => 'desc'])
			->find();
		if($tutor) {
			return [
				'type' => Order::TYPE_TUTOR,
				'id' => $tutor['id']
			];
		}
		
		return false;
	}
	
	
	public function rebate($orderId) {
		try {
			$order = Order::get($orderId);
			if(!$order) {
				throw new Exception('订单不存在');
			}
			
			if($order['rebate_status'] != Order::REBATE_CAL) {
				throw new Exception('非待计算返利订单');
			}
			
			switch ($order['order_type']) {
				case Order::TYPE_TUTOR:
					//导师大赛订单
					$res = $this->tutorRebate($order);
					break;
				case Order::TYPE_PLAN:
					//创业大赛订单
					$res = $this->planRebate($order);
					break;
				case Order::TYPE_GIFT:
					//代言人订单
					$res = $this->giftRebate($order);
					break;
				case Order::TYPE_REWARD:
					//赠酒订单
					$res = $this->rewareRebate($order);
					break;
				default:
					//普通或拼团订单
					$res = $this->normalRebate($order);
			}
			
			
			return $res;
		} catch (Exception $e) {
			$this->errorMsg = $e->getMessage();
			return false;
		}
		
	}
	
	/**
	 * 导师大赛订单处理
	 * @param Order $order
	 * @return array
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	private function tutorRebate(Order $order)
	{
		$userId = $order['user_id'];
		
		//查找是否有参加的团
		$teamMember = Db::name('tutorMember')
			->where(['user_id' => $userId, 'status' => TutorMember::STATUS_NORMAL])
			->find();
		
		$teamId = $teamMember ? $teamMember['team_id'] : '';
		$itemRes = TutorSaleItem::addRow($teamId, $userId,$order['id'], $order['number']);
		if(!$itemRes) {
			$this->errorMsg = '导师订单处理销量出错';
			return false;
		}
		
		$rebateRes = Db::name('order')
			->where(['id' => $order['id']])
			->update(['rebate_status' => Order::REBATE_DONE]);
		if(!$rebateRes) {
			$this->errorMsg = '更改订单返利状态出错';
		}
		
		
		return true;
	}
	
	/**
	 * 创业大赛订单处理
	 * @param Order $order
	 * @return bool
	 * @throws \think\db\exception\DataNotFoundException
	 * @throws \think\db\exception\ModelNotFoundException
	 * @throws \think\exception\DbException
	 */
	private function planRebate(Order $order)
	{
		$planId = $order['activity_id'];
		$userId = $order['recommend_user_id'];
		$member = Db::name('teamMember')->alias('m')
			->join('businessPlan p', 'm.business_plan_id = p.id', 'left')
			->join('user u', 'm.user_id = u.id', 'left')
			->where(['m.business_plan_id' => $planId, 'm.user_id' => $userId])
			->field('m.id, m.team_id, m.business_plan_id, p.number, p.sale_number, m.user_id, u.level')
			->find();
		
		if(!$member) {
			$rebateRes = Db::name('order')
				->where(['id' => $order['id']])
				->update(['rebate_status' => Order::REBATE_DONE]);
			if(!$rebateRes) {
				$this->errorMsg = '更改订单返利状态出错';
				return false;
			}
			return true;
		}
		
		$planModel = new BusinessPlan();
		$saleRes = $planModel->addSaleNumber($planId, $member['team_id'], $member['id'], $order['number'], $member['number'], $member['sale_number'], $member['user_id'], $order['id']);
		
		$agent = null;
		$promotion = null;
		//给战区加数量
		if($member['level'] == User::LEVEL_PROMOTION) {
			$promotion = Promotion::get(['user_id' => $userId]);
			if($promotion && $promotion['agent_shop_id']) {
				$agent = AgentShop::get($promotion['agent_shop_id']);
			}
		} else if($member['level'] > User::LEVEL_PROMOTION) {
			$agent = AgentShop::get(['user_id' => $userId]);
		}
		
		//参与大赛的，只给战区加数量
		if($agent && $agent['theater_id']) {
			$shopModel = new AgentShop();
			$numRes = $shopModel->addNumber($agent['theater_id'], $order['number'], $order['amount'], $order['number'], $order['id'], $agent['id'], $promotion ? $promotion['id'] : '');
			if(!$numRes) {
				$this->errorMsg = '添加大赛战区销售数量出错';
				return false;
			}
		}
		if(!$saleRes) {
			$this->errorMsg = $planModel->getError();
			return false;
		}
		
		$rebateRes = Db::name('order')
			->where(['id' => $order['id']])
			->update(['rebate_status' => Order::REBATE_DONE]);
		if(!$rebateRes) {
			$this->errorMsg = '更改订单返利状态出错';
			return false;
		}
		
		return true;
	}
	
	/**
	 * 代言人赠送订单处理(广东给推荐人返10%佣金，其它地方按普通订单处理）
	 * @param Order $order
	 * @return bool|void
	 * @throws Exception
	 * @throws \think\exception\DbException
	 */
	private function giftRebate(Order $order)
	{
		if($order['area'] == User::AREA_SZ) {
			//深圳的推荐人获得20%佣金到余额,归属的发展中心获得10%
			if($order['recommend_user_id']) {
				$recommendUser = User::get($order['recommend_user_id']);
				$userId = $order['user_id'];
				$promotionOrder = AgentOrder::get(['user_id' => $userId, 'status' => AgentOrder::STATUS_Y]);
				$setting = Db::name('ruleSz')->find();
				$commission = 0;
				if($setting && $setting['promoter_rebate_ratio'] > 0) {
					$commission = round($promotionOrder['amount'] * $setting['promoter_rebate_ratio']/100, 2);
				}
//				if($recommendUser['level'] == User::LEVEL_WAREHOUSE) {
//					$commission = $promotionOrder['amount'] * 0.1;
//				} else {
//					$commission = $promotionOrder['amount'] * 0.2;
//				}
				$commissionModel = new Commission();
				$goods = Db::name('orderGoods')->where(['order_id' => $order['id']])->find();
				if($commission > 0 && $recommendUser['level'] > User::LEVEL_USER) {
					$commissionRes = $commissionModel->rebate($order['recommend_user_id'], $order['user_id'], $order['id'], $goods['goods_id'], $goods['id'], $commission, '推荐代言人佣金', $commissionModel::TYPE_RECOMMEND);
					
					if(!$commissionRes) {
						$this->errorMsg = '添加推荐人佣金出错';
						return false;
					}
				}
			}
			
			$rebateRes = Db::name('order')
				->where(['id' => $order['id']])
				->update(['rebate_status' => Order::REBATE_WAIT]);
			if(!$rebateRes) {
				$this->errorMsg = '更改订单返利状态出错';
			}
			
			return true;
		} else {
			return $this->normalRebate($order);
		}
	}
	
	/**
	 * 买3送1订单处理
	 * @param Order $order
	 */
	private function rewareRebate(Order $order)
	{
		return $this->normalRebate($order);
	}
	
	/**
	 * 普通订单处理
	 * @param Order $order
	 */
	private function normalRebate(Order $order)
	{
		if($order['area'] == User::AREA_SZ) {
			$model = new RuleSz();
			$res = $model->rebate($order['id']);
		} else {
			$model = new Order();
			$res = $model->rebate($order['id']);
		}
		
		if(!$res) {
			$this->errorMsg = $model->getError();
			return false;
		}
		
		//查找是否有返利
		$rebateRow = Db::name('commission')
			->where(['order_id' => $order['id']])
			->find();
		
		
		$rebateRes = Db::name('order')
			->where(['id' => $order['id']])
			->update(['rebate_status' => $rebateRow ? Order::REBATE_WAIT : Order::REBATE_NULL_REBATE]);
		if(!$rebateRes) {
			$this->errorMsg = '更改订单返利状态出错';
			return false;
		}
		
		return true;
	}
	
	
	/**
	 * 根据核销代理分配订单归属
	 * @param $agentId 代理
	 * @param $number 核销数量
	 * @return bool
	 */
	public function addParentDestoryNumber($agent, $number, $orderId, $goodsId, $specId, $code) {
		$parentAgentIds = [];
		$parentFiles = [
			'warehouse_id',
			'center_id',
			'theater_id'
		];
		
		foreach ($parentFiles as $file) {
			if($agent[$file] && $agent[$file] != $agent['id']) {
				$parentAgentIds[] = $agent[$file];
			}
		}
		
		if($parentAgentIds) {
			Db::startTrans();
			try {
				$model = new AgentShip();
				$agents = Db::name('agentShop')
					->where(['id' => ['in', $parentAgentIds]])
					->select();
				foreach ($agents as $agent) {
					//添加记录
					$shipRes = $model->addRecore($orderId, $agent['id'], $goodsId, $specId, $number, $code, $model::TYPE_SON);
					if(!$shipRes) {
						throw new Exception('添加上级核销记录出错');
					}
					//添加核销数量
					
					$numberRes = Db::name('agentShop')
						->where(['id' => $agent['id']])
						->setInc('destory_number', $number);
					if(!$numberRes) {
						throw new Exception('添加上级核销数量出错');
					}
				}
				
				Db::commit();
			} catch (Exception $e) {
				Db::rollback();
				$this->errorMsg = $e->getMessage();
				return false;
			}
		}
		
		return true;
	}
	
}
